<?php

namespace model;

include_once APP_PATH . './model/Model.php';
include_once APP_PATH . './model/Log.php';

class Category extends Model
{
    public function getCategoryList()
    {
        $sql = "SELECT * FROM category order by category_id desc";
        $categoryList = $this->queryAll($sql);
        return $categoryList;
    }

    public function CategoryAdd($categoryName, $categoryDesc)
    {
        // 判断是否有同名称的分类
        $sql = "select * from category where category_name='$categoryName'";
        $category = $this->queryOne($sql);
        if ($category) {
            echo '分类已经存在。';
            echo '<a href="javascript:void(0)" onclick="history.back();">返回上一页</a>';
            exit();
        }

        $addTime = time();
        $updateTime = $addTime;

        $sql = "insert into category (category_name, category_desc, add_time, update_time) 
  values ('$categoryName', '$categoryDesc', '$addTime', '$updateTime')";
        $result = $this->exec($sql);
        if ($result) {
            $logModel = new Log();
            $logModel->write([
                'action' => 'category_add',
                'content' => '增加分类成功',
                'category_name' => $categoryName,
                'category_desc' => $categoryDesc,
            ]);
        }

        return $result;
    }

    public function getCategoryById($categoryId)
    {
        $sql = "select * from category where category_id='$categoryId'";
        $category = $this->queryOne($sql);
        return $category;
    }

    public function CategoryEdit($categoryId, $categoryName, $categoryDesc)
    {
        // 判断是否有同名称的分类？

        $updateTime = time();

        $sql = "update category set category_name='$categoryName', category_desc='$categoryDesc',  update_time='$updateTime' 
  where category_id='$categoryId'";
        $result = $this->exec($sql);
        //var_dump($db->errorInfo());
        if ($result) {
            $log = new Log();
            $log->write([
                'action' => 'category_edit',
                'content' => '编辑分类成功',
                'category_id' => $categoryId,
                'category_name' => $categoryName,
                'category_desc' => $categoryDesc,
            ]);
        }
        return $result;
    }

    public function CategoryDelete($categoryId)
    {
        $existSql = "select * from article where category_id='$categoryId' limit 1";
        $articleResult = $this->queryOne($existSql);
        if ($articleResult) {
            echo '分类下有文章，请先删除相关文章。';
            echo '<a href="javascript:void(0)" onclick="history.back();">返回上一页</a>';
            exit();
        }

        $sql = "delete from category where category_id='$categoryId'";
        $result = $this->exec($sql);

        return $result;
    }

}